package com.holly.common_view;

import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.NumberPicker;
import android.widget.TextView;

import java.util.Calendar;
import java.util.Locale;

/**
 * @author Joey Huang（QQ:273179370）
 * @created 2016/9/8
 */
public class TimePickerDialog extends Dialog {
    public static final int YEAR = 1 << 1;
    public static final int MONTH = 1 << 2;
    public static final int DAY = 1 << 3;
    public static final int HOUR = 1 << 4;
    public static final int MINUTE = 1 << 5;
    public static final int SECOND = 1 << 6;
    /**
     * 格式 yyyy-MM-dd HH:mm:ss
     * 2016-11-23 19:30:15
     */
    public static final int ALL = YEAR | MONTH | DAY | HOUR | MINUTE | SECOND;
    /**
     * 格式 yyyy-MM-dd
     */
    public static final int DATE = YEAR | MONTH | DAY;
    /**
     * 格式 HH:mm:ss
     */
    public static final int TIME = HOUR | MINUTE | SECOND;
    /**
     * 格式 yyyy-MM
     */
    public static final int YEAR_MONTH = YEAR | MONTH;
    /**
     * 格式 MM-dd
     */
    public static final int MONTH_DAY = MONTH | DAY;
    /**
     * 格式 HH:mm
     */
    public static final int HOUR_MINUTE = HOUR | MINUTE;

    private final String TAG = "joey_" + getClass().getSimpleName();
    private int mType;
    private NumberPicker mNpYear;
    private NumberPicker mNpMonth;
    private NumberPicker mNpDay;
    private NumberPicker mNpHour;
    private NumberPicker mNpMinute;
    private NumberPicker mNpSecond;
    private TextView mTvYear;
    private TextView mTvMonth;
    private TextView mTvDay;
    private TextView mTvHour;
    private TextView mTvMinute;
    private TextView mTvSecond;
    private Calendar mCalendar;

    private OnTimeChangedListener mOnTimeChangedListener;

    public TimePickerDialog(Context context) {
        this(context, ALL);
    }

    public TimePickerDialog(Context context, int type) {
        super(context, R.style.DialogStyle);
        init(type);
    }

    private void init(int type) {
        //点击屏幕外关闭
        setCanceledOnTouchOutside(true);

        Context themeContext = getContext();
        //设置为底部
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);

        View view = LayoutInflater.from(themeContext).inflate(R.layout.dialog_picker, null);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        setContentView(view, layoutParams);
        initView(view);
        setType(type);
    }

    private void initView(View view) {
        mNpYear = (NumberPicker) view.findViewById(R.id.np_year_customize);
        mNpMonth = (NumberPicker) view.findViewById(R.id.np_month_customize);
        mNpDay = (NumberPicker) view.findViewById(R.id.np_day_customize);
        mNpHour = (NumberPicker) view.findViewById(R.id.np_hour_customize);
        mNpMinute = (NumberPicker) view.findViewById(R.id.np_minute_customize);
        mNpSecond = (NumberPicker) view.findViewById(R.id.np_second_customize);
        mNpYear.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mNpMonth.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mNpDay.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mNpHour.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mNpMinute.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mNpSecond.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS);
        mTvYear = (TextView) view.findViewById(R.id.tv_year_customize);
        mTvMonth = (TextView) view.findViewById(R.id.tv_month_customize);
        mTvDay = (TextView) view.findViewById(R.id.tv_day_customize);
        mTvHour = (TextView) view.findViewById(R.id.tv_hour_customize);
        mTvMinute = (TextView) view.findViewById(R.id.tv_minute_customize);
        mTvSecond = (TextView) view.findViewById(R.id.tv_second_customize);
        initNumberView();
        final TextView btCancel = (TextView) view.findViewById(R.id.tv_cancel_customize);
        btCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TimePickerDialog.this.dismiss();
            }
        });

        TextView btOk = (TextView) view.findViewById(R.id.tv_ok_customize);
        btOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringBuffer resultBuffer = new StringBuffer();
                StringBuilder patternBuilder=new StringBuilder();
                if ((mType & YEAR) != 0) {
                    resultBuffer.append("-");
                    resultBuffer.append(mNpYear.getValue());
                    patternBuilder.append("-");
                    patternBuilder.append("yyyy");
                }

                if ((mType & MONTH) != 0) {
                    resultBuffer.append("-");
                    if (mNpMonth.getValue() < 10) {
                        resultBuffer.append(0);
                        resultBuffer.append(mNpMonth.getValue());
                    } else {
                        resultBuffer.append(mNpMonth.getValue());
                    }
                    patternBuilder.append("-");
                    patternBuilder.append("MM");
                }

                if ((mType & DAY) != 0) {
                    resultBuffer.append("-");
                    if (mNpDay.getValue() < 10) {
                        resultBuffer.append(0);
                        resultBuffer.append(mNpDay.getValue());
                    } else {
                        resultBuffer.append(mNpDay.getValue());
                    }
                    patternBuilder.append("-");
                    patternBuilder.append("dd");
                }

                int indexOf = resultBuffer.indexOf("-");
                if (indexOf != -1) {
                    resultBuffer.deleteCharAt(indexOf);
                    patternBuilder.deleteCharAt(indexOf);
                }

                if ((mType & HOUR) != 0) {
                    resultBuffer.append(":");
                    if (mNpHour.getValue() < 10) {
                        resultBuffer.append(0);
                        resultBuffer.append(mNpHour.getValue());
                    } else {
                        resultBuffer.append(mNpHour.getValue());
                    }
                    patternBuilder.append(":");
                    patternBuilder.append("HH");
                }

                if ((mType & MINUTE) != 0) {
                    resultBuffer.append(":");
                    if (mNpMinute.getValue() < 10) {
                        resultBuffer.append(0);
                        resultBuffer.append(mNpMinute.getValue());
                    } else {
                        resultBuffer.append(mNpMinute.getValue());
                    }
                    patternBuilder.append(":");
                    patternBuilder.append("mm");
                }

                if ((mType & SECOND) != 0) {
                    resultBuffer.append(":");
                    if (mNpSecond.getValue() < 10) {
                        resultBuffer.append(0);
                        resultBuffer.append(mNpSecond.getValue());
                    } else {
                        resultBuffer.append(mNpSecond.getValue());
                    }
                    patternBuilder.append(":");
                    patternBuilder.append("ss");
                }

                indexOf = resultBuffer.indexOf(":");
                if (indexOf != -1) {
                    resultBuffer.replace(indexOf, indexOf + 1, " ");
                    patternBuilder.replace(indexOf, indexOf + 1, " ");
                }
                TimePickerDialog.this.dismiss();
                onDataChanged(resultBuffer.toString(),patternBuilder.toString());
            }
        });
    }

    private void initNumberView() {
        //默认大小
        mNpYear.setMinValue(2000);
        mNpYear.setMaxValue(2020);
        mNpMonth.setMinValue(1);
        mNpMonth.setMaxValue(12);
        mNpDay.setMinValue(1);
        mNpDay.setMaxValue(31);
        mNpHour.setMinValue(0);
        mNpHour.setMaxValue(23);
        mNpMinute.setMinValue(0);
        mNpMinute.setMaxValue(59);
        mNpSecond.setMinValue(0);
        mNpSecond.setMaxValue(59);

        mNpMonth.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int value) {
                if (value < 10) {
                    return "0" + value;
                }
                return String.valueOf(value);
            }
        });
        mNpDay.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int value) {
                if (value < 10) {
                    return "0" + value;
                }
                return String.valueOf(value);
            }
        });
        mNpHour.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int value) {
                if (value < 10) {
                    return "0" + value;
                }
                return String.valueOf(value);
            }
        });
        mNpMinute.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int value) {
                if (value < 10) {
                    return "0" + value;
                }
                return String.valueOf(value);
            }
        });
        mNpSecond.setFormatter(new NumberPicker.Formatter() {
            @Override
            public String format(int value) {
                if (value < 10) {
                    return "0" + value;
                }
                return String.valueOf(value);
            }
        });
        mNpYear.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                if (mCalendar == null) {
                    mCalendar = Calendar.getInstance(Locale.CHINA);
                }
                mCalendar.set(newVal, mNpMonth.getValue() - 1, 1);
                int maxDayCount = mCalendar.getActualMaximum(Calendar.DATE);
                int value = mNpDay.getValue();
                mNpDay.setMaxValue(maxDayCount);
                if (value > maxDayCount) {
                    mNpDay.setValue(maxDayCount);
                } else {
                    mNpDay.setValue(value);
                }
            }
        });
        mNpMonth.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
            @Override
            public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                if (mCalendar == null) {
                    mCalendar = Calendar.getInstance(Locale.CHINA);
                }
                mCalendar.set(mNpYear.getValue(), newVal - 1, 1);
                int maxDayCount = mCalendar.getActualMaximum(Calendar.DATE);
                int value = mNpDay.getValue();
                mNpDay.setMaxValue(maxDayCount);
                if (value > maxDayCount) {
                    mNpDay.setValue(maxDayCount);
                } else {
                    mNpDay.setValue(value);
                }
            }
        });
    }

    public void setType(int type) {
        mType = type;
        if ((mType & YEAR) == 0) {
            mTvYear.setVisibility(View.GONE);
            mNpYear.setVisibility(View.GONE);
        } else {
            mTvYear.setVisibility(View.VISIBLE);
            mNpYear.setVisibility(View.VISIBLE);
        }

        if ((mType & MONTH) == 0) {
            mTvMonth.setVisibility(View.GONE);
            mNpMonth.setVisibility(View.GONE);
        } else {
            mTvMonth.setVisibility(View.VISIBLE);
            mNpMonth.setVisibility(View.VISIBLE);
        }
        if ((mType & DAY) == 0) {
            mTvDay.setVisibility(View.GONE);
            mNpDay.setVisibility(View.GONE);
        } else {
            mTvDay.setVisibility(View.VISIBLE);
            mNpDay.setVisibility(View.VISIBLE);
        }

        if ((mType & HOUR) == 0) {
            mTvHour.setVisibility(View.GONE);
            mNpHour.setVisibility(View.GONE);
        } else {
            mTvHour.setVisibility(View.VISIBLE);
            mNpHour.setVisibility(View.VISIBLE);
        }
        if ((mType & MINUTE) == 0) {
            mTvMinute.setVisibility(View.GONE);
            mNpMinute.setVisibility(View.GONE);
        } else {
            mTvMinute.setVisibility(View.VISIBLE);
            mNpMinute.setVisibility(View.VISIBLE);
        }
        if ((mType & SECOND) == 0) {
            mTvSecond.setVisibility(View.GONE);
            mNpSecond.setVisibility(View.GONE);
        } else {
            mTvSecond.setVisibility(View.VISIBLE);
            mNpSecond.setVisibility(View.VISIBLE);
        }
    }

    public void setOnTimeChangedListener(OnTimeChangedListener onTimeChangedListener) {
        mOnTimeChangedListener = onTimeChangedListener;
    }

    public void onDataChanged(String time, String pattern) {
        Log.w(TAG, "onDataChanged: " + time);
        if (mOnTimeChangedListener != null) {
            mOnTimeChangedListener.onTimeChanged(time,pattern);
        }
    }

    public interface OnTimeChangedListener {
        void onTimeChanged(String time, String pattern);
    }

    /**
     * 设置初始的年月日时分秒，如果不设置，可以传入-1
     * @param year 年（2000-2020）
     * @param month 月（1-12）
     * @param day 日（1-31）
     * @param hour 时（0-23)
     * @param minute 分(0-59)
     * @param second 秒(0-59)
     */
    public void setSelect(int year, int month, int day, int hour, int minute, int second) {
        if (year != -1) {
            mNpYear.setValue(year);
        }
        if (month != -1) {
            mNpMonth.setValue(month);
        }
        if (day != -1) {
            mNpDay.setValue(day);
        }
        if (hour != -1) {
            mNpHour.setValue(hour);
        }
        if (minute!= -1) {
            mNpMinute.setValue(minute);
        }
        if (second != -1) {
            mNpSecond.setValue(second);
        }
    }

    @Override
    public void show() {
        //设置为底部
        Window window = getWindow();
        WindowManager wm = (WindowManager) getContext()
                .getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = width; //设置宽度
        window.setAttributes(lp);
        super.show();
    }
}
